package com.example.demo.itext;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.*;

public class Text {
    public static void main(String[] args) throws DocumentException, IOException {

    //    convert("D:\\XISOFT\\gbk.txt","D:\\XISOFT\\gbk.pdf");
        convert("D:\\XISOFT\\utf8.txt","D:\\XISOFT\\utf8.pdf");
    }
    public static void convert(String srcFilestr,String descFilestr) throws IOException, DocumentException {
        File srcfile=new File(srcFilestr);
        File attachPdfFile=new File(descFilestr);
        //创建文本对象
        Document document = new Document(PageSize.A4);
        attachPdfFile.createNewFile();
        //PdfWriter是iText编辑PDF文档的编辑器
        // 为该Document创建一个Writer实例
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(attachPdfFile));
        //打开document
        document.open();
        //插入段落文字
        try ( FileReader fileReader = new FileReader(srcfile);
              BufferedReader bufferedReader = new BufferedReader(fileReader);){
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                Paragraph textgraph = new Paragraph(line);
                textgraph.setAlignment(Element.ALIGN_LEFT);
                textgraph.setSpacingBefore(40f);
                document.add(textgraph);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        //关闭 document
        document.close();
        writer.close();
    }
}
